package com.killer.mianshibaodian.utils;

import android.database.Cursor;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by killer on 2016/4/17.
 */
public class QuestionDao {
    public static void insertData(Map<String, Object> map) {
        String sql = "insert into ques_ans (question,answer) values(?,?)";
        Log.i("killer","insertData                  "+map.get("question").toString());
        Globals.util.getWritableDatabase().execSQL(sql,new Object[]{map.get("question").toString(),map.get("answer").toString()});
    }

    //查询全部
    public static List<Map<String,Object>> loadData(){
        List<Map<String,Object>> values = new ArrayList<>();
        String sql ="select id,question,answer from ques_ans";
        Cursor c= Globals.util.getReadableDatabase().rawQuery(sql,null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();
            map.put("question",c.getInt(0)+""+c.getString(1));
            map.put("answer",c.getInt(2));
            values.add(map);
            c.moveToNext();
        }
        c.close();

        return  values;
    }

    public static List<Map<String, Object>> loadPage(int pagenum, int pagesize, String keyword) {
        List<Map<String, Object>> values = new ArrayList<>();
        String sql = "select id,question,answer from ques_ans where question like ? limit ?,?";

        Cursor c = Globals.util.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"%",pagesize*pagenum-pagesize+"",pagesize+""});
        c.moveToNext();
        while (!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();

            map.put("question",c.getInt(0)+""+c.getString(1));
            map.put("answer",c.getString(2));
           // Log.i("answeranswer   ",c.getString(2)+"");
            values.add(map);
            c.moveToNext();
        }
        c.close();
        return values;

    }

    //模糊查询查询记录数
    public static int getCount(String keyword){
        int recordCount = 0;
        String sql = "select count(*) from ques_ans where question like ?";
        Cursor c = Globals.util.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"%"});
        c.moveToFirst();
        //c.getCount();
        recordCount = c.getInt(0);
        c.close();

        return recordCount;
    }

    //删除全部数据
    public static void deleteAllData(){
        String sql = "delete from ques_ans";
        Globals.util.getWritableDatabase().execSQL(sql);
    }
}
